<?php

namespace app\base\controller\miniapp\member;

use app\base\logic\LogsLogic;

use app\base\model\CouponModel;

use app\base\model\member\MemberCouponModel;

use app\base\model\member\MemberIntegralModel;

use app\base\model\member\MemberModel;

use app\BaseController;

use think\facade\Db;



class Coupon extends BaseController{

    //获取我的优惠券

    public function getMemberCoupons(){

        $type = $this->request->param('type/d',1);

        $where = [

            ['shop_id','=',$this->request->shopId],

            ['member_id','=', $this->request->memberId]

        ];

        $today = date('Y-m-d', $this->request->time());

        $member_coupon_model=new MemberCouponModel();

        if($type == 1){

            $where[] = ['status','=',0];

            $where[] = ['valid_end_time','>=',$today];

            $member_coupon_model=$member_coupon_model->where($where);

        }else{

            $map1 = $where; $map2=$where;

            $map1[]=['status','=',1];

            $map2[]=['valid_end_time','<',$today];

            $member_coupon_model=$member_coupon_model->whereOr([ $map1, $map2 ]);

        }

        $coupons = $member_coupon_model->order(['member_coupon_id' => 'desc'])

            ->page($this->request->page)->limit($this->request->limit)

            ->field('member_coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,status')

            ->select()->toArray();

        return $this->success([

            'coupons' => $coupons

        ]);

    }



    //获取可领取的优惠券

    public function getCouponDatas(){

        $today = date('Y-m-d', $this->request->time());

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['quota','>',0],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

            ['is_integral_exchange','=',0]

        ];

        $return = [];

        $return['hasIds'] = [];

        //如果memberId 不为空的情况下

        if($this->request->memberId){

            if(null === $member = MemberModel::find($this->request->memberId)){

                return $this->error('用户登录状态不正确',100);

            }

            if($member->shop_id != $this->request->shopId){

                return $this->error('用户登录状态不正确',100);

            }

            $where[]= $member->level === null ? ['type_id','=',1] : ['type_id','IN',[1,3]];



            $hasIds = MemberCouponModel::where([

                    ['member_id','=', $this->request->memberId],

                    ['shop_id','=', $this->request->shopId],

                    ['type_id','=',1]

                ])->column('coupon_id') ?? [];

            $return['hasIds'] = $hasIds;

        }else{ //非登录情况只显示普通券

            $where[]=['type_id','=',1];

        }



        $coupons = CouponModel::where($where)

            ->order(['update_time'=>'desc','add_time'=>'desc'])

            ->limit($this->request->limit)->page($this->request->page)

            ->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit')

            ->select()->toArray();

        $return['coupons']=$coupons;

        return $this->success($return);

    }



    //获取可兑换的优惠券

    public function getExchangeCouponDatas(){

        $today = date('Y-m-d', $this->request->time());

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['status','=',1],

            ['is_delete','=',0],

            ['quota','>',0],

            ['start_time','<=',$today],

            ['end_time','>=',$today],

            ['is_integral_exchange','=',1],

           

        ];

        if($this->request->member->level === null){ //非会员只显示1

            $where[] =  ['type_id','=',1];

        }else{

            $where[] =  ['type_id','in',[1,3]];

        }

        



        $coupons = CouponModel::where($where)

            ->order(['update_time'=>'desc','add_time'=>'desc'])

            ->limit($this->request->limit)->page($this->request->page)

            ->field('coupon_id,name,coupon_money,money_limit,exchange_integral')

            ->select()->toArray();

        $return['datas']=$coupons;

        return $this->success($return);

    }





    //领取优惠券

    public function getCoupon(){

        $coupon_id = $this->request->param('coupon_id/d');

        if(empty($coupon_id)){

            return $this->error('请选择要领取的优惠券');

        }



        $today=date('Y-m-d',$this->request->time());

        $is_exist=MemberCouponModel::where([

            ['member_id','=', $this->request->memberId],

            ['shop_id','=', $this->request->shopId],

            ['coupon_id','=',$coupon_id],

            ['type_id','=',1]

        ])->find();

        if($is_exist){

            return $this->error('此优惠券您已领过');

        }



        if(null === $coupon = CouponModel::where('coupon_id',$coupon_id)->lock(true)->find()){

            return $this->error('优惠券不存在');

        }

        if($coupon->is_delete == 1 || $coupon->shop_id != $this->request->shopId ){

            return $this->error('优惠券不存在');

        }

        if($coupon->status == -1){

            return $this->error('优惠券已经下架');

        }

        if($coupon->quota <= 0){

            return $this->error('优惠券已经领完了');

        }

        if($coupon->start_time > $today || $coupon->end_time < $today){

            return $this->error('优惠券已经过期了');

        }

        if($coupon->is_integral_exchange==1){

            return $this->error('该优惠券只能积分兑换无法领取');

        }



        $member=$this->request->member;

        $type_id = $member->level === null ? 1 : 3;

        if($coupon->type_id > $type_id){

            return $this->error('该券为会员券，普通用户无法领取');

        }



        $coupon->quota = $coupon->quota - 1;

        $coupon->take_count = $coupon->take_count + 1;

        $mCoupon = new  MemberCouponModel();



        $mCoupon->save([

            'shop_id'       => $this->request->shopId,

            'member_id'     => $this->request->memberId,

            'type_id'       => 1,

            'coupon_id'     => $coupon->coupon_id,

            'name'          => $coupon->name,

            'coupon_money'  => $coupon->coupon_money,

            'money_limit'   => $coupon->money_limit,

            'valid_bg_time' => $coupon->valid_bg_time,

            'valid_end_time'=> $coupon->valid_end_time,

            'status'        => 0

        ]);

        $coupon->save();



        LogsLogic::coupon($this->request->shopId,$member->member_id,1,8,$mCoupon->member_coupon_id,'',0);



        return $this->success([]);

    }



    //领取优惠券

    public function exchangeCoupon(){

        $coupon_id = $this->request->param('coupon_id/d');

        if(empty($coupon_id)){

            return $this->error('请选择要领取的优惠券');

        }



        $today=date('Y-m-d',$this->request->time());



        if(null === $coupon = CouponModel::where('coupon_id',$coupon_id)->lock(true)->find()){

            return $this->error('优惠券不存在');

        }

        if($coupon->is_delete == 1 || $coupon->shop_id != $this->request->shopId ){

            return $this->error('优惠券不存在');

        }

        if($coupon->status == -1){

            return $this->error('优惠券已经下架');

        }

        if($coupon->quota <= 0){

            return $this->error('优惠券已经兑换完了');

        }

        if($coupon->start_time > $today || $coupon->end_time < $today){

            return $this->error('优惠券已经过期了');

        }

        if($coupon->is_integral_exchange==0){

            return $this->error('该优惠券无法用积分兑换');

        }



        $member=$this->request->member;

        $type_id = $member->level === null ? 1 : 3;

        if($coupon->type_id > $type_id){ //会员允许兑换普通券

            return $this->error('会员券普通用户无法兑换');

        }



        $integral=$coupon->exchange_integral;



        Db::startTrans();

        try{

            //操作积分

            $myIntegral = MemberIntegralModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$this->request->memberId],

                ['expire_time','>=',$this->request->time()]

            ])->sum('remain_integral');

            if($myIntegral < $integral){

                Db::rollback();

                return $this->error('用户积分不够兑换的#1');

            }

            $needIntegral = $integral;

            while (true){

                $where = [

                    ['shop_id','=',$this->request->shopId],

                    ['member_id','=',$this->request->memberId],

                    ['expire_time','>=',$this->request->time()],

                    ['remain_integral','>',0]

                ];

                $integralModel = MemberIntegralModel::where($where)->order(['expire_time'=>'asc'])->find();

                if(null === $integralModel){

                    Db::rollback();

                    return $this->error('用户积分不够扣除的#2');

                }

                if($integralModel->remain_integral < $needIntegral){

                    $needIntegral = $needIntegral - $integralModel->remain_integral;

                    $integralModel->remain_integral = 0;

                }else{

                    $integralModel->remain_integral = $integralModel->remain_integral - $needIntegral;

                    $needIntegral = 0;

                }

                $integralModel->save();

                if($needIntegral <= 0) break;

            }



            if(!LogsLogic::integral($this->request->shopId,$this->request->memberId,-1,7,$integral,'',0)){

                Db::rollback();

                return $this->error('操作失败');

            }



            //优惠券操作

            $coupon->quota = $coupon->quota - 1;

            $coupon->take_count = $coupon->take_count + 1;

            $mCoupon = new  MemberCouponModel();



            $mCoupon->save([

                'shop_id'       => $this->request->shopId,

                'member_id'     => $this->request->memberId,

                'type_id'       => 3,

                'coupon_id'     => $coupon->coupon_id,

                'name'          => $coupon->name,

                'coupon_money'  => $coupon->coupon_money,

                'money_limit'   => $coupon->money_limit,

                'valid_bg_time' => $coupon->valid_bg_time,

                'valid_end_time'=> $coupon->valid_end_time,

                'status'        => 0

            ]);

            $coupon->save();



            LogsLogic::coupon($this->request->shopId,$this->request->memberId,1,4,$mCoupon->member_coupon_id,'',0);



            Db::commit();

            return $this->success([]);

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }

}

